package net.liteheaven.xblib.widget.edittext;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;

import net.liteheaven.xblib.common.convert.StringUtil;

/**
 * 
 * 固定行数EditText 
 * @author  LiangYu
 * @data:  2015-3-6 下午2:47:19 
 * @version:  V1.0
 */
public class FixedLineCountEditText extends EditText {
	
    private int mMaxLineCount = 10;

	public FixedLineCountEditText(Context context) {
		super(context);
		init();
	}

	public FixedLineCountEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public FixedLineCountEditText(Context context, AttributeSet attrs,
			int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init();
	}
	
	private void init(){
		setInputType(0);
		setSingleLine(false);
        setMaxLineCount(mMaxLineCount);
		addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				int a = 0;
				a++;
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				do1(s);
			}
			
			private void do1(Editable s){
				int lineCount = getLineCount();
				//int lineCount = StringUtil.getSubStringCount(getText().toString(), "\n") + 1;
				String str = s.toString();

				if (lineCount > mMaxLineCount){
					StringBuffer sb = new StringBuffer(str);
					StringUtil.removeLineAtFirst(sb);
					setText(sb);
				}
			}
		});
	}
	
	public void appendLine(CharSequence text) {
		int count = getLineCount();
		if (count == 0){
			super.append(text, 0, text.length());
		}
		else{
			super.append("\n" + text);
		}
	}

    public void setMaxLineCount(int line){
        mMaxLineCount = line;
        setMinLines(line);
        setMaxLines(line);
        setLines(line);
    }
}
